package org.peterf.foxish.texture;

import org.peterf.foxish.R;
import org.peterf.foxish.opengl20.OpenGLUtil;
import org.peterf.foxish.util.EngineException;
import org.peterf.foxish.util.ResourceUtil;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class TextureUtil {

    public static Bitmap getBitmap(int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Resources res = ResourceUtil.getResources();
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static BitmapFactory.Options getBitmapInfo(int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        options.inJustDecodeBounds = true;
        Resources res = ResourceUtil.getResources();
        BitmapFactory.decodeResource(res, resId, options);
        return options;
    }

    public static Texture getTexture(Bitmap bitmap) {
        Texture texture = new Texture();
        texture.width = bitmap.getWidth();
        texture.height = bitmap.getHeight();
        int t = OpenGLUtil.createTexture();
        if (t != 0) {
            OpenGLUtil.bindTexture(t);
            if (!OpenGLUtil.uploadTexture(bitmap)) {
                OpenGLUtil.deleteTexture(t);
                t = 0;
            }
        }
        if (t == 0) {
            throw new EngineException(R.string.foxish_err_texture_fail);
        }
        texture.name = t;
        return texture;
    }
    
    public static Texture getTexture(int resId) {
        Bitmap bitmap = getBitmap(resId);
        Texture texture = getTexture(bitmap);
        bitmap.recycle();
        return texture;
    }

}
